/**
 * @fileOverview
 * Paginate Blogger Posts.
 * 
 * This file is the function version of the orignal source code.
 * It is under the licence "Apache License 2.0".
 * @author Tzu-yang Tsai
 */

/**
 * @namespace
 */
var blogger_extention = {};

/**
 * @function
 * Setting up the pagination of blogger posts
 * @param {int} [posts_displayed=10] the number of posts displayed on each page.
 * @param {function} display_function the function display the pages. The function has 3 arguments. They are "the current page number", "the array of the links of each page", and "the number of pages". The default value is the inner function defaultDisplayFunction
 */
blogger_extention.pagination = function(posts_displayed, display_function){
	var MAX_POSTS_ENTRY = 500;	//The maxium number of feed.entry. Even if it sets "max-results", it won't have more 
	posts_displayed = posts_displayed || 10;
	
	//if(typeof display_function != "function")
	//	display_function = defaultDisplayFunction;

	/** The callback function of AJAX loading. */
	function setFeed(posts){
		if(typeof posts == "string")
			feed = JSON.parse(feed);
		if(typeof posts != "object")
			return;
		//var posts = feed.feed.entry;
		var numOfPages = parseInt(posts.length / posts_displayed);
		/*
		 * Check the page num of the current page.
		 */
		var currentPage = undefined;
		var thisPageFirstPostID = document.getElementsByClassName("date-posts")[0].getElementsByClassName("post")[0].getElementsByTagName("a")[0]["name"];
		if(!thisPageFirstPostID) return;
	
	
	
		for(var i = 0; i < posts.length; i++){
			var postID = posts[i].id["$t"];
			postID = postID.split("-").pop();
		
			if(thisPageFirstPostID == postID){
				currentPage = parseInt(i / posts_displayed);
				break;
			}
		}
	
	
		var urls=[];
		for(i = 0; i < posts.length; i+= posts_displayed){
			var timestemp = posts[i]["published"]["$t"];
			timestemp = timestemp.substr(0, timestemp.indexOf(".")) + timestemp.substr(timestemp.indexOf("+"));
			timestemp = encodeURIComponent(timestemp);
		
			var pageurl = location.pathname;
			if((pageurl == "/"  || (pageurl == "/search" && location.href.indexOf("q=") < 0))   && i < posts_displayed){
				//it is the first page without any searching or tag viewing
				pageurl = "/";
				urls.push(pageurl);
				continue;
			}else if(pageurl == "/"){
				pageurl = "/search";
			}
			pageurl+= "?Page=" + (urls.length + 1) + "&updated-max=" + timestemp + "&max-results=" + posts_displayed + "&by-date=true";
		
			if(location.href.indexOf("q=") > 0){
				var searchQuery, qindex = location.search.indexOf("q=") + 2;
				if(location.search.indexOf("&") >= 0)
					searchQuery = location.search.substring(qindex, location.search.indexOf("&", qindex));
				else
					searchQuery = location.search.substring(qindex);
				pageurl += "&q=" + searchQuery;
			}
		
		
			urls.push(pageurl);
		}
		display_function(currentPage+1, urls, urls.length);
	
	}
	if(location.pathname.indexOf("/p/") >=0 || location.pathname.indexOf(".html")>=0){
		//if it is a page or post, do nothing.
		return;
	}


	var url = "/feeds/posts/summary?alt=json&max-results=2147483647";
	if(location.pathname.indexOf("label") >= 0){
		var label = location.pathname.split("/").pop();
		url += "&category=" + decodeURIComponent(label);
		posts_displayed = 20;
	}
	if(location.search.indexOf("q=") >= 0){
		var qindex = location.search.indexOf("q=") + 2;
		var searchQuery;
		if(location.search.indexOf("&") >= 0)
			searchQuery = location.search.substring(qindex, location.search.indexOf("&", qindex));
		else
			searchQuery = location.search.substring(qindex);
	
		url += "&q=" + searchQuery;
	
		if(location.search.indexOf("by-date") >= 0){
			var byDateIndex = location.search.indexOf("by-date");
			var byDateQuery = location.search.substring(qindex, location.search.indexOf("&", byDateIndex));
			byDateQuery = byDateQuery.substring(byDateQuery.indexOf("=")+1);
			if(byDateQuery == "false")
				return;//since it is sorted by correlation. It cannot use pagenation.
		}
		url+="&by-date=true"
		posts_displayed = 20;
	}

	var feeds = []

	var xmlhttp = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			//load successful
			var f = JSON.parse(xmlhttp.responseText);
			for(var i in f.feed.entry)
				feeds.push(f.feed.entry[i]);
			
			if(f.feed.entry.length < MAX_POSTS_ENTRY){
				setFeed(feeds);
				return;
			}
			
			//the number of entries of the feed loaded is more then (or equal to) MAX_POSTS_ENTRY
			//so loading more feed to check
			var _d = f.feed.entry[f.feed.entry.length - 1]["published"]["$t"];
			var d = new Date(_d);
			
			var timezone = _d.substr(19),_t = 0
			
			if(timezone.substr(0,1) == "+" || timezone.substr(0,1) == "-"){
				_t = (timezone.substr(1,2) * 1000 * 60 * 60 + timezone.substr(4,2) * 1000 * 60)
				if(timezone.substr(0,1) == "-"){
					_t *= -1
				}
			}
			
			
			var d = new Date(_d);
			d.setTime(d.getTime() - 1000/* -1 second */ + _t /* Add timezone */); 
			var date = d.getUTCDate() 
			
			var printfNum = function(val){
				if(val < 10)
					return "0" + val;
				return val
			}
			
			var newPublishDate = d.getUTCFullYear() + "-" + printfNum(d.getUTCMonth() + 1) + "-" + printfNum(d.getUTCDate()) + "T" + printfNum(d.getUTCHours()) + ":" + printfNum(d.getUTCMinutes()) + ":" + printfNum(d.getUTCMinutes())  + timezone;
			
			xmlhttp.open("GET", url + "&published-max=" + encodeURIComponent(newPublishDate), true);
			xmlhttp.send();
		}
	}
	xmlhttp.open("GET", url,true);
	xmlhttp.send();
}
